<?php

declare(strict_types=1);

namespace cosy\framework\command\curd;

use cosy\framework\command\BaseMake;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\facade\Db;

/**
 * ClassName Validate
 * Description TODO
 * Author BTC
 * Date 2023/11/4 13:58
 **/
class Validate extends BaseMake
{
    protected $type = 'validate';

    protected function configure()
    {
        $this->setName('cosy:validate')
            ->addArgument('module', Argument::REQUIRED, 'Please input your class name')
            ->addArgument('table', Argument::REQUIRED, 'Please input your model name')
            ->setDescription('create a validate');
    }

    protected function execute(Input $input, Output $output)
    {
        $table = trim($input->getArgument('table'));
        $tableName = substr($table, strlen(env('DB_PREFIX')));
        $array = explode('_', $tableName);
        foreach ($array as $key => $val){
            $array[$key] = ucfirst($val);
        }
        $mapper = implode('', $array);
        

        $module = trim($input->getArgument('module'));
        $name = 'app\\' . $module . '\\' . $this->type . '\\' . $mapper;
//        $model = 'app\\' . $module . '\\model\\' . $mapper . 'Models';

        $this->build($name, $table);

        $output->writeln('<info>' . $this->type . ':' . $name . ' created successfully.</info>');
    }

    // 填充模板
    public function build($name, $model)
    {
        $stub = $this->getStub();
        $namespace = trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\');
        $class = str_replace($namespace . '\\', '', $name);
        $className = $class . ucfirst($this->type);

        $fields = Db::table($model)->getFields();
        $rule = "";
        $message = "";
        foreach ($fields as $field) {
            if($field['name'] == end($fields)['name']){
                $rule = $rule . "        '" . $field['name'] . "' => 'require'";
                $message = $message . "        '" . $field['name'] . ".require' => '" . $field['comment'] . "',";
            }else{
                $rule = $rule . "        '" . $field['name'] . "' => 'require'," . PHP_EOL;
                $message = $message . "        '" . $field['name'] . ".require' => '" . $field['comment'] . "'," . PHP_EOL;
            }

        }
//        $modelSapce = trim(implode('\\', array_slice(explode('\\', $model), 0, -1)), '\\');
//        $modelName = str_replace($modelSapce . '\\', '', $model);

        $search = [
            '{%createTime%}',
            '{%className%}',
            '{%namespace%}',
            '{%rule%}',
            '{%message%}'
        ];

        $replace = [
            date('Y-m-d H:i'),
            $className,
            $namespace,
            $rule,
            $message
        ];

        file_put_contents($this->getPathName($name), str_replace($search, $replace, $stub));

        return true;
    }

    /**
     * 获取模板
     * @return string
     */
    protected function getStub()
    {
        $path = __DIR__ . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR . $this->type . '.stub';
        return file_get_contents($path);
    }

    protected function getClassName(string $name): string
    {
        if (strpos($name, '\\') !== false) {
            return $name;
        }

        if (strpos($name, '@')) {
            [$app, $name] = explode('@', $name);
        } else {
            $app = '';
        }

        if (strpos($name, '/') !== false) {
            $name = str_replace('/', '\\', $name);
        }

        return $this->getNamespace($app) . '\\' . $name;
    }

    protected function getPathName(string $name): string
    {
        $name = str_replace('app\\', '', $name);
        $name = $name . ucfirst($this->type);

        return $this->app->getBasePath() . ltrim(str_replace('\\', '/', $name), '/') . '.php';
    }
}